package cn.com.yto56.coresystem.business.msg.soa.controller;

import cn.com.yto56.coresystem.business.msg.soa.biz.IYtoMsgForJsonBiz;
import cn.com.yto56.coresystem.common.msg.util.base.StringUtils;
import cn.com.yto56.coresystem.common.msg.util.data.DataTypeChangeTool;
import cn.com.yto56.coresystem.common.msg.util.domain.AppResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by wangrui on 2017/6/12.
 */
@Controller
@RequestMapping(value = "/ytoMsgServiceForJson")
public class YtoMsgServiceForJsonController implements IYtoMsgForJsonBiz {
    @Autowired
    YtoMsgServiceController ytoMsgServiceController;

    @RequestMapping(value = "/doInterface", method = RequestMethod.GET)
    @Override
    public String doInterface(@RequestParam(value = "interfaceName") String interfaceName, @RequestParam(value = "paramsJson") String paramsJson) {
        Map params = DataTypeChangeTool.jsonToMap(paramsJson);
        AppResult appResult = getAppResult(interfaceName, params);
        return DataTypeChangeTool.beanToJSON(appResult);
    }

    public AppResult getAppResult(String interfaceName, Map map) {
        AppResult result = new AppResult();
        if (StringUtils.isNotBlank(interfaceName)) {
            try {
                Class c = ytoMsgServiceController.getClass();
                Method method = c.getMethod(interfaceName, new Class[]{Map.class});
                //获得参数Object
                Object[] arguments = new Object[]{map};
                //执行方法
                result = (AppResult) method.invoke(ytoMsgServiceController, arguments);
                if (result == null) {
                    result = new AppResult();
                    result.setResultFlag(false);
                    result.setResultMessage("接口调用失败，不存在该接口或无法器已关闭");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } else {
            result.setResultFlag(false);
            result.setResultMessage("接口名称不能为空");
        }

        return result;
    }
}
